package com.dawnClass.controller;


import com.dawnClass.service.RegisterService;
import com.dawnClass.util.RSAUtils;
import com.dawnClass.util.ServiceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class RegisterController {
    @Autowired
    private RegisterService registerService;
    // 添加新用户
    @PostMapping("/consumer")
    public ModelAndView regist(String consumerName, Long consumerTel, String consumerPassword, HttpSession session){
        System.out.println("前端返回的密码："+consumerPassword);
        System.out.println("session id:"+session.getId());
        ModelAndView mav = new ModelAndView();
        ServiceResponse serviceResponse = registerService.regist(consumerTel);
        if(serviceResponse.getdata().equals("existence")){
            System.out.println("存在");
            mav.addObject("loginMsg","手机号码已被注册过请返回登录");
            mav.setViewName("login/register");
        }else{
            registerService.save(consumerName , consumerTel , consumerPassword);
            mav.setViewName("login/login");
        }
        return mav;
    }
    @GetMapping("/publickey")
    @ResponseBody
    public ServiceResponse resregister() {

        return registerService.getPublicKey();
    }

    @GetMapping("/encrypted")
    @ResponseBody
    public ServiceResponse password(@RequestParam("encrypted") String encrypted) {
        System.out.println("密文: ");
        System.out.println(encrypted);

        String privateKey = registerService.getPrivateKey();

        try {
            System.out.println("解密中.....");
            String decryptedBytes = RSAUtils.privateDecrypt(encrypted, RSAUtils.getPrivateKey(privateKey));
            System.out.println("解密后：" + decryptedBytes);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
